<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import axios from '@/request/http'
import { useMainStore } from '@/store/main'
import yspglService from '@/api/yspgl'
import wjfwSerivce from '@/api/wjfw'
import detailItem from './components/detail-item.vue'
import { useRoute } from 'vue-router'
import { mlxxMainStore } from '@/store/mlxx'
const mlxxStore = mlxxMainStore()
const store = useMainStore()
const route = useRoute()

defineProps({
  gdjdList: {
    type: Object,
    default: null,
  },
})

const emit = defineEmits(['ysplbChangeEvent'])

// 生命周期
onMounted(() => {
  //
})

const activeName = ref('first')

const getWjxqxx = (data: any) => {
  if (Object.keys(data).length === 0) return (wjxqxxList.value = [])
  if (data.wjbh && data.wjbh.length !== 0) {
    wjxqxxList.value = [data]
  } else {
    wjxqxxList.value = []
  }
  checkboxData.value = []
}

// 复选框绑定数据
const checkboxData = ref<any[]>([])
const wjxqxxList = ref<any>([])
const accept = computed(() => {
  if (store.$state.nodeTreeData?.fbh === 'gd0020001') return '.mp3,.m4a,.amr'
  if (store.$state.nodeTreeData?.fbh === 'gd0020002') return '.mp4,.mkv,.mov,.avi,.wmv'
  else return '.jpg,.jpeg,.png,.bmp'
})
/**
 * 上传文件
 */
const singleUploadFile = async (file: any) => {
  const lastStr = file.name.slice(file?.name.lastIndexOf('.'))
  if (!accept.value.includes(lastStr?.toLowerCase())) {
    if (store.$state.nodeTreeData?.fbh === 'gd0020001') {
      return ElMessage.warning(
        `不支持上传${lastStr}格式的文件，现只支持上传.mp3，.m4a，.amr类型的文件`,
      )
    } else if (store.$state.nodeTreeData?.fbh === 'gd0020002') {
      return ElMessage.warning(
        `不支持上传${lastStr}格式的文件，现只支持上传.mp4，.mkv，.mov，.avi，.wmv类型的文件`,
      )
    } else {
      return ElMessage.warning(
        `不支持上传${lastStr}格式的文件，现只支持上传.jpg，.jpeg，.png，.bmp类型的文件`,
      )
    }
  }
  const formData = new FormData()
  formData.append('file', file)
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const res = await wjfwSerivce.upload(formData).catch((err) => {
    fileRef.value.value = ''
    !err.isError && ElMessage({ type: 'warning', message: err.message })
    return {
      code: err.code,
      data: {},
      message: err.message,
    }
  })
  const i = file.name.lastIndexOf('.')
  const resoult = await yspglService
    .uploadSxwj(
      {
        file: res.wjbh,
        dabh: store.$state.nodeTreeData?.dabh,
        mlbh: store.$state.nodeTreeData?.bh,
        jzsmjlbh: route.query.jzsmjlbh,
        wjkzm: file.name.slice(i + 1),
        wjxsmc: file.name.slice(0, i),
      },
      route.query.ajbh as string,
    )
    .catch((err) => {
      fileRef.value.value = ''
      !err.isError && ElMessage({ type: 'warning', message: err.message })
      return {
        code: err.code,
        data: {},
        message: err.message,
      }
    })

  if (resoult.data === true) {
    ElMessage({ type: 'success', message: '上传文件成功' })
    emit('ysplbChangeEvent')
    loading.close()
    fileRef.value.value = ''
    return resoult || ''
  }
  loading.close()
}

/*
 * 上传文件（成功抛出刷新）
 */
const fileRef = ref()
const uploadClick = () => {
  fileRef.value.multiple = false
  fileRef.value.click()
}

// 上传文件（成功抛出刷新）
const uploadFile = async (e: any) => {
  const file = e.target.files[0]
  await singleUploadFile(file)
  emit('ysplbChangeEvent')
}

const checkChange = (data: any) => {
  checkboxData.value = data
}

/*
 * 刷新
 */
const refresh = () => {
  emit('ysplbChangeEvent')
}

/* 展示详情 */
const currentItem = ref<any>({})
const loadDetail = (item: any) => {
  currentItem.value = { ...item }
}

/* 关闭详情 */
const closeDetail = () => {
  currentItem.value = {}
}

/*
 * 删除（成功抛出刷新）
 */
const deleteWj = () => {
  ElMessageBox.confirm('是否删除选中的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const params = {
      dabh: checkboxData.value[0].dabh,
      mlbh: checkboxData.value[0].mlbh,
      wjbh: checkboxData.value[0].wjbh,
      jzsmjlbh: route.query.jzsmjlbh,
    }
    yspglService
      .deleteSxwj(params, route.query.ajbh as string)
      .then(() => {
        ElMessage({ type: 'success', message: '删除成功' })
        checkboxData.value = []
        emit('ysplbChangeEvent')
        wjxqxxList.value = []
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}

// 点击
const checkboxSelect = (item: any, e: any) => {
  e.preventDefault()
  const checkboxIndex = checkboxData.value.findIndex((el) => el.wjbh === item.wjbh)
  if (checkboxIndex >= 0) {
    checkboxData.value.splice(checkboxIndex, 1)
  } else {
    checkboxData.value = [item]
  }
  // if (e.shiftKey) {
  //   const lastSelectedIndex = wjxqxxList.value.findIndex((selected: any) => selected === item)
  //   const currentIndex = wjxqxxList.value.indexOf(item)
  //   const startIndex = Math.min(lastSelectedIndex, currentIndex)
  //   const endIndex = Math.max(lastSelectedIndex, currentIndex)
  //   checkboxData.value = wjxqxxList.value.slice(startIndex, endIndex + 1)
  // }
}

const disabled = computed(
  () =>
    (store.nodeTreeData?.bh !== store.jzsmZpNode?.bh &&
      store.nodeTreeData?.fbh !== store.jzsmZpNode?.bh) ||
    !mlxxStore.isUnlockReadOnly,
)
defineExpose({ getWjxqxx, closeDetail })
</script>
<template>
  <div class="container">
    <el-tabs v-model="activeName" class="demo-tabs" type="card">
      <el-tab-pane label="音像" name="first">
        <div class="content">
          <!-- 头部 -->
          <div class="top">
            <div class="topLeft">
              <img src="@/assets/images/yjqqs.png" alt="" />
              <p>{{ store.$state.nodeTreeData?.mc }}</p>
            </div>
            <div class="topRight">
              <button
                class="btn_operation"
                @click="refresh"
                :disabled="store.nodeTreeData?.cj === 1 || !store.nodeTreeData?.cj"
              >
                <div class="btn-sx"></div>
                刷新
              </button>

              <button
                class="btn_operation"
                @click="deleteWj"
                :disabled="
                  store.$state.nodeTreeData?.cj !== 2 ||
                  disabled ||
                  !checkboxData.length ||
                  !mlxxStore.isUnlockReadOnly
                "
              >
                <div class="btn-sc"></div>
                删除
              </button>
              <!-- <el-input placeholder="请输入查询关键字" :suffix-icon="Search" /> -->
            </div>
          </div>
          <!-- 内容区域 -->
          <div class="center">
            <div
              class="writingsBox"
              v-if="
                !(!store.nodeTreeData.sfkbj || store.nodeTreeData.sfkbj === 'N') &&
                wjxqxxList.length
              "
            >
              <div class="writingsItem" v-for="item in wjxqxxList" :key="item.wjbh">
                <div
                  class="item-content"
                  @click="checkboxSelect(item, $event)"
                  :style="{
                    border: checkboxData.some((el) => el.wjbh === item.wjbh)
                      ? '3px solid #409eff'
                      : '',
                  }"
                >
                  <div class="content-header">
                    <el-checkbox-group v-model="checkboxData" @change="checkChange">
                      <el-checkbox :value="item"></el-checkbox>
                    </el-checkbox-group>
                    <img src="@/assets/images/ellipse.png" alt="" />
                  </div>
                  <template
                    v-if="
                      store.$state.nodeTreeData?.mllxdm === 'gd0020001' ||
                      store.$state.nodeTreeData?.mllxdm === 'gd0020002'
                    "
                  >
                    <div class="content-img" @dblclick.stop="loadDetail(item)">
                      <img src="@/assets/images/play.png" />
                    </div>
                  </template>
                  <template v-if="store.$state.nodeTreeData?.mllxdm === 'gd0020003'">
                    <div class="photo-imgs" @dblclick.stop="loadDetail(item)">
                      <img :src="`${axios.defaults.baseURL}/fpi/wjfw/download?wjbh=${item.wjbh}`" />
                    </div>
                  </template>
                  <div class="content-footer" v-if="item.jcztmc">{{ item.ysplbmc }}</div>
                </div>
                <div class="pageNumber">1</div>
                <!-- <div class="title">{{ element.label }}</div> -->
              </div>
            </div>
            <el-empty v-else class="noMessage"></el-empty>
          </div>
          <!-- 底部按钮 -->
          <div
            class="bottomButton"
            v-if="
              !(!store.nodeTreeData.sfkbj || store.nodeTreeData.sfkbj === 'N') &&
              store.nodeTreeData?.cj === 2 &&
              store.nodeTreeData?.fbh === store.jzsmZpNode?.bh &&
              mlxxStore.isUnlockReadOnly
            "
          >
            <el-button type="primary" @click="uploadClick">上传文件</el-button>
            <div class="secret">*严禁传输涉密信息</div>
            <input
              style="display: none"
              accept=".png,.jpg,.jpeg,.bmp"
              type="file"
              @change="uploadFile"
              ref="fileRef"
            />
          </div>
          <!-- 展示详情 -->
          <detail-item
            :current-item="currentItem"
            class="detail-wrapper"
            @close="closeDetail"
            v-if="currentItem.wjbh"
          ></detail-item>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  .content {
    width: 100%;
    height: 100%;
    padding: 5px;
    display: flex;
    flex-direction: column;
    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #dae4f1;
      padding-bottom: 5px;
      margin-bottom: 5px;
      .topLeft {
        display: flex;

        img {
          padding-right: 5px;
        }
        p {
          font-weight: 600;
        }
      }
    }
    .buttomGroup {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-bottom: 5px;
      .rowbutton {
        display: flex;
      }
    }

    .center {
      padding: 15px;
      background-color: #f7f8f9;
      height: 100%;
      overflow: auto;
      display: flex;
      flex-direction: column;
      .headerButtomGroup {
        .header-text {
          color: #4a76ab;
        }
        .header-text + .header-text {
          margin-left: 10px;
        }
        .header-avtive {
          color: #fff;
          background-color: #3c89d0;
        }
      }

      .writingsBox {
        overflow-y: auto;
        max-height: 100%;
        display: flex;
        flex-wrap: wrap;
        margin-top: 10px;
        .writingsItem {
          width: 212px;
          padding: 0 16px 10px 0;
          display: flex;
          flex-direction: column;

          .item-content {
            display: flex;
            flex-direction: column;
            flex: 1;
            flex-shrink: 0;
            background-color: #fff;
            box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            border: 3px solid transparent;
            .content-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 0 10px;
              img {
                width: 15px;
                height: 15px;
              }
            }

            .content-img {
              margin: 0 10px 10px 10px;
              flex: 1;
              flex-shrink: 0;
              background-color: #b3c6d1;
              display: flex;
              justify-content: center;
              align-items: center;

              & > img {
                width: 100%;
                height: 212px;
              }
            }

            .photo-imgs {
              margin: 0 10px 10px 10px;
              flex: 1;
              flex-shrink: 0;
              img {
                width: 100%;
                height: 212px;
              }
            }

            .content-footer {
              width: 100%;
              text-align: center;
              padding: 5px 0;
              background-color: #f7c863;
            }
          }

          .pageNumber {
            height: 26px;
            line-height: 26px;
            text-align: center;
          }
        }
      }

      .noMessage {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .bottomButton {
      display: flex;
      align-items: center;
      margin-top: 10px;
      .secret {
        margin-left: 10px;
        color: red;
      }
    }
  }
}

.export-excel {
  li {
    text-align: center;
    height: 30px;
    line-height: 30px;
    cursor: pointer;
    &:hover {
      background-color: #ecf5ff;
      color: #266df5;
    }
  }
}
.detail-wrapper {
  width: 100%;
  height: 100%;
  background-color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 999;
}
</style>
